<template>
  <div class="energy">
    <ListTab
      v-model="tabStatus"
      :show-header="!showMobilePage"
      :tabs="tabs"
      :max-badge="{ num: 100, str: '99+' }"
      is-table
      @tabClick="handleTabClick" />
    <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="min-fill-page energy-list">
      <div v-if="!showMobilePage" class="filter">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          is-show-config
          show-search-btn
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
        <createBtn v-if="hasRouteAuth('energy:energyList:creat')" style="margin-right: 10px;" @click.native="toCreate"/>
        <MoreOpeator
          ref="moreOpeatorRef"
          :list="moreOperatorList"
        />
      </div>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 300px;">
          <u-table
            v-if="list.items.length"
            ref="energyTableRef"
            :data="list.items"
            :border="true"
            :row-height="rowHeight()"
            :height="setTableHeight"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable"
            @sort-change="sortMethod">
            <u-table-column
              :fixed="selectFixed"
              align="center"
              type="selection"
              width="50"/>
            <u-table-column :min-width="handleTdWidth()" align="left" label="审批单号" label-class-name="diy-cell" class-name="diy-cell">
              <template slot-scope="scope" slot="header">
                <div class="diyHeader">{{ scope.column.label }}</div>
              </template>
              <template slot-scope="scope">
                <processSn :is-expedited="scope.row.isExpedited">
                  <div v-if="scope.row.energyNum" style="cursor:pointer;color:#406EFF;" @click="toDetail(scope.row)">
                    <ToolTip :content="handleSnNumber(scope.row.energyNum)" is-can-click @handelClick="toDetail(scope.row)" />
                  </div>
                  <div v-else>--</div>
                </processSn>
              </template>
            </u-table-column>
            <u-table-column align="left" label="月份" min-width="90" prop="monthTime" sortable="custom">
              <template slot-scope="scope">
                <div>
                  <ToolTip :content="format(scope.row.monthTime,'YYYY/MM')" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="填写人数">
              <template slot-scope="scope">
                <div v-if="scope.row.allPersonNum"><span style="color:red">{{ scope.row.allPersonNum - scope.row.unfillNum }}</span>{{ `/${scope.row.allPersonNum }` }}</div>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="账号数量" min-width="120" prop="accountNum" sortable="custom">
              <template slot-scope="scope">
                <div>
                  <ToolTip :content="scope.row.accountNum" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="状态">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.status || scope.row.status===0" :open-delay="800" class="item" placement="top" effect="dark">
                  <div slot="content">{{ scope.row.status | energyStatus }}</div>
                  <StatusText
                    :color="['#FFBC3D', '#FD8546', '#FF4E5F', '#999', '#31CC9C', '#406EFF'][scope.row.status]"
                    :text="scope.row.status | energyStatus" />
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="当前节点">
              <template slot-scope="scope">
                <div>
                  <ToolTip :content="scope.row.currentNode" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="当前处理人" min-width="110">
              <template slot-scope="scope">
                <div>
                  <ToolTip :content="scope.row.currentHandler" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请人" min-width="110">
              <template slot-scope="scope">
                <div>
                  <ToolTip :content="scope.row.proposer" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请人部门" min-width="110">
              <template slot-scope="scope">
                <div>
                  <ToolTip :content="scope.row.proposerDepartmentName" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建人部门" min-width="110">
              <template slot-scope="scope">
                <div>
                  <ToolTip :content="scope.row.attributionMatrixName" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="备注">
              <template slot-scope="scope">
                <div>
                  <ToolTip :content="scope.row.remark" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建人">
              <template slot-scope="scope">
                <CheckUserInfo :user-id="scope.row.creatorId" :label="scope.row.createUser" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建时间" min-width="160" prop="createTime" sortable="custom">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.createTime,'YYYY/MM/DD HH:mm:ss')" />
              </template>
            </u-table-column>
            <u-table-column :width="operateWidth" align="left" label="操作" fixed="right">
              <template slot-scope="scope">
                <div class="flex-center">
                  <div v-if="scope.row.status !== 0 && !showMobilePage" class="button-text br" @click="toDetail(scope.row)">查看</div>
                  <MoreOpeator
                    :list="[
                      {
                        label: '查看',
                        handelClick: () => {toDetail(scope.row)},
                        auth: scope.row.status !== 0 && showMobilePage
                      },{
                        label: '复制',
                        handelClick: () => {handlerCreateNew(scope.row)},
                        disabled: scope.row.status === 0 || !hasRouteAuth('energy:energyList:creat')
                      },{
                        label: '编辑',
                        handelClick: () => {toEdit(scope.row)},
                        disabled: setEditDisable(scope.row)
                      },{
                        label: '删除',
                        handelClick: () => {toDelete(scope.row)},
                        disabled: setDelDisable(scope.row)
                      }
                    ]"
                  >
                    <div v-if="!showMobilePage" slot="button" class="button-text">更多<i class="el-icon-arrow-down"/></div>
                    <el-image v-else slot="button" :src="operateBtns" class="table-dropdown-img"/>
                  </MoreOpeator>
                </div>
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-else-if="!isInit" style="margin-bottom: 24px" />
        </div>
        <DiversAuditorDialog ref="auditorDialog" :can-empty="false" @handleSender="handleBatchSender" />
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-show="list.total > 0"
            :current-page.sync="page"
            :page-size="perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-search-btn
              show-mobile-icon
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus" />
            <MoreOpeator
              ref="moreOpeatorRef"
              :list="moreOperatorList"
              show-mobile-icon
            />
            <createBtn
              v-if="hasRouteAuth('energy:energyList:creat')"
              mobile-table
              @click.native="toCreate"/>
          </template>
          <template v-else>
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
            <div style="flex: 1;" />
            <el-pagination
              v-show="list.total > 0"
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios';// 取消未完成请求
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
// 组件
import ListTab from '@/components/ListTab';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createBtn from '@/components/Common/baseComponent/createBtn';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
// fitter
import { energyStatus } from '@/filters/status';
import { expeditedOptions } from '@/filters/status';
// api
import { tabList, energyList, deleteEneegy } from '@/api/energy';
import { getDepartmentAll } from '@/api/config';
import { format } from '@/filters/date';
import { showModal } from '@/utils/message';
import { commonOptions } from '@/utils/tools';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { PROCESS_TYPE } from '@/utils/const/process';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import filterObjStoreMixin from '@/mixins/filterObjStore';
import copyLink from '@/mixins/copyLink';
import schedule from '@/mixins/schedule';
import tableSelections from '@/mixins/tableSelections';

export default {
  filters: {
    energyStatus
  },
  components: {
    ListTab,
    EmptyPlaceholder,
    createBtn,
    MoreOpeator,
    DiversAuditorDialog
  },
  mixins: [TableAdaptive, tableSelections, mobileTable, filterObjStoreMixin, copyLink, schedule],
  data() {
    return {
      tabs: [],
      list: {
        items: [],
        total: 0
      },
      isInit: true,
      tableRefName: 'energyTableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      isUmyTable: true,
      tabStatus: -1,
      page: 1,
      perPage: 20,
      paramsObj: {},
      sortName: '',
      sortType: '',
      listLoading: false,
      deptTreeList: [],
      cancelToken: null
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'energyNum', name: '审批单号', labelWidth: '100px', type: 'input' },
        { keyword: 'currentHandler', name: '当前处理人', labelWidth: '100px', type: 'input' },
        { keyword: 'currentNode', name: '当前节点', labelWidth: '100px', type: 'input' },
        { keyword: 'createUser', name: '创建人', labelWidth: '100px', type: 'input' },
        { keyword: 'comment', name: '评论', type: 'input', labelWidth: '100px' },
        { keyword: 'approvalComment', name: '审批意见', type: 'input', labelWidth: '100px' },
        { keyword: 'proposer', name: '申请人', labelWidth: '100px', type: 'input' },
        // 下拉
        { keyword: 'status', name: '状态', type: 'select', options: commonOptions },
        { keyword: 'attributionMatrix', name: '创建人部门', type: 'cascaderSelect', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'proposerDepartmentId', name: '申请人部门', type: 'cascaderSelect', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'isExpedited', name: '是否加急', type: 'select', options: expeditedOptions },
        // 日期
        { keyword: 'monthTime', name: '月份', labelWidth: '100px', timeType: 'monthrange', type: 'rangeDate', format: 'yyyy/MM', startPlaceholder: '开始月份', endPlaceholder: '结束月份' },
        { keyword: 'createTime', name: '创建时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' }
      ];
      return arr;
    },
    rangeKeyArr() {
      return [{
        attr: 'createTime',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time'
      }, {
        attr: 'monthTime',
        start: 'monthStartTime',
        end: 'monthEndTime',
        type: 'time'
      }];
    },
    moreOperatorList() {
      return [
        { label: '批量抄送', handelClick: this.handleSendMsg },
        { label: '复制链接', handelClick: this.batchCopyLink }
      ];
    }
  },
  watch: {
    list: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true
    }
  },
  created() {
    this.queryDeptTreeList();
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'energyCreate' || from.name === 'energyEdit') {
      to.meta.isRedirectCreate = true;
    } else {
      to.meta.isRedirectCreate = false;
    }
    next();
  },
  activated() {
    if (this.$route.meta.isRedirectCreate) {
      this.fetchData();
    } else {
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      if (!this.isInit || !hasDefaultPresetFilter) {
        this.fetchData(true);
      }
    }
  },
  methods: {
    hasRouteAuth,
    format,
    getDetailLink(item) {
      if (!item.status) return '';
      return `${location.origin}#/operate/energy/detail?energyId=${item.id}&processId=${item.processId}`;
    },
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    getTabs() {
      const params = this.formatParams();
      delete params.tabStatus;
      tabList(params).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.tabs = res.data;
      }).catch(err => {
        console.log(err);
      });
    },
    handleTabClick(id) {
      this.isInit = true;
      this.tabStatus = id;
      this.list = { items: [] };
      this.fetchData(true);
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    fetchData(reset = false) {
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();// 用于取消请求
      this.cancelToken = source;
      this.getTabs();
      this.listLoading = true;
      if (reset) this.page = 1;
      const params = this.formatParams();
      energyList(params, source.token).then(res => {
        this.isInit = false;
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
      }).catch(err => {
        this.isInit = false;
        this.listLoading = false;
        console.log(err);
      });
    },
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      paramsRangeFormat(this.rangeKeyArr, params);
      params.page = this.page;
      params.perPage = this.perPage;
      params.tabStatus = this.tabStatus;
      params.sortType = this.sortType || '';
      params.sortName = this.sortName || '';
      return params;
    },
    setEditDisable(data) {
      return !(data.status === 0 && data.creatorId === this.userInfo.id);
    },
    setDelDisable(data) {
      const statusArr = [0, 2, 3, 5];// 草稿、已撤销、未过审、待提交
      return !(statusArr.includes(data.status) && (data.creatorId === this.userInfo.id || this.hasRouteAuth('energy:energyList:delete')));// 除审批中和已完成状态且为创建人或者有删除权限
    },
    toCreate() {
      this.$router.push({
        name: 'energyCreate'
      });
    },
    toEdit(row) {
      this.$router.push({
        name: 'energyEdit',
        query: {
          energyId: row.id
        }
      });
    },
    toDetail(row) {
      this.filterObjStore(PROCESS_TYPE.ENERGY);
      this.$router.push({
        name: 'energyDetail',
        query: {
          energyId: row.id,
          processId: row.processId,
          fromList: 1
        }
      });
    },
    toDelete(row) {
      showModal('确定删除该精力分配?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        deleteEneegy(row.id).then(res => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.resetItemSelected(row.id);
          this.fetchData();
        }).catch(err => { console.log(err); });
      }).catch(() => {
        return false;
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    handlerCreateNew(row) { // 再次发起（复制）
      const routeUrl = this.$router.resolve({
        name: 'energyEdit',
        query: {
          energyId: row.id,
          reapplyId: row.processId,
          createNew: 1
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
	.energy{
		.energy-list{
			margin: 16px 16px 0 16px;
			background-color: #fff;
			padding: 20px 24px 55px 24px;
		}
    .border-left {
      position: relative;
      padding-left:6px;
      margin-left: 6px;
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        margin-top: -7px;
        width: 1px;
        background: #ddd;
        height: 14px;
      }
    }
		.filter {
			display: flex;
			align-items: center;
      margin-bottom: 16px;
		}
	}
</style>
